<template>
  <!-- 添加或修改盘点计划对话框 -->
  <el-dialog :title="title" v-if="open" v-model="open" width="1300px" append-to-body>
    <selectMaterialForm ref="selectMaterialForm" @ok="selectOk"></selectMaterialForm>
    
    <custom-dialog ref="customDialog" @ok="customerOk"></custom-dialog>
    <div v-loading="loading">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px" :inline="true">
        <!-- 客户信息 -->
        <el-card shadow="always" :body-style="{ padding: '20px' }">
          <template #header>
            <div style="font-size: 16px; font-weight: bold">客户信息</div>
          </template>
          <el-form-item label="跟单类型:" prop="followTypeId">
            <el-select
              @change="(val) => getFollowStatus(val)"
              :disabled="isView"
              v-model="form.followTypeId"
              clearable
              reserve-keyword
              placeholder="请选择跟单类型"
            >
              <el-option v-for="item in followTypeList" :key="item.id" :label="item.typeName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="跟单日期:" prop="followDate">
            <el-date-picker
              style="width: 100%"
              v-model="form.followDate"
              :disabled="isView"
              value-format="YYYY-MM-DD hh:mm:ss"
              type="date"
              placeholder="跟单日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="跟单号:" prop="clueNumber">
            <el-input disabled v-model="form.clueNumber" placeholder="请输入线索编号" clearable />
          </el-form-item>
          <el-form-item label="客户名称:" prop="supplierId" @click="showCustomer">
                <el-input :disabled="isLink || isView" v-model="form.supplierName" placeholder="请选择客户" size="normal" clearable suffix-icon="search"></el-input>
          </el-form-item>
          <el-form-item label="联系人:" prop="contact">
            <el-select :disabled="isView" @change="contactChange" v-model="form.contact" clearable reserve-keyword placeholder="请选择联系人">
              <el-option v-for="item in contacts" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="跟单来源:" prop="clueSource">
            <el-select :disabled="isView" v-model="form.clueSource" clearable reserve-keyword placeholder="请选择跟单来源">
              <el-option v-for="item in clueSource" :key="item.id" :label="item.sourceName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="岗位:" prop="postName">
            <el-input disabled v-model="form.postName" placeholder="岗位"></el-input>
          </el-form-item>
          <el-form-item label="所属区域:">
            <el-cascader v-if="(form.country || '').indexOf(',') > -1" style="width: 100%" disabled :options="options" v-model="selectedOptions">
            </el-cascader>
            <el-select disabled v-else v-model="form.country" value-key="" placeholder="请选择所属区域" clearable filterable>
              <el-option v-for="item in areaList" :key="item.id" :label="item.areaName" :value="item.id + ''"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="联系方式:" prop="contactWay">
            <el-input disabled v-model="form.contactWay" placeholder="联系方式"></el-input>
          </el-form-item>

          <el-form-item label="详细地址:">
            <el-input :disabled="isView" style="width: 1043px" v-model="form.addDetail" placeholder="详细地址"></el-input>
          </el-form-item>
        </el-card>
        <el-card shadow="always" style="margin: 10px 0" :body-style="{ padding: '20px' }">
          <template #header>
            <div style="font-size: 16px; font-weight: bold">跟单信息</div>
          </template>
          <el-form-item label="项目名称:" prop="clueName">
            <el-input :disabled="isView" v-model="form.clueName" placeholder="请输入项目名称" clearable />
          </el-form-item>

          <el-form-item label="跟单阶段:" prop="followStageId">
            <el-select :disabled="isView" v-model="form.followStageId" clearable reserve-keyword placeholder="请选择跟单阶段">
              <el-option v-for="item in followStatus" :key="item.id" :label="item.name" :value="item.id" >
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
                  {{ item.progressCoefficient }}
                </span>
              </el-option>
            </el-select>          
            
          </el-form-item>
          <el-form-item label="预计成交金额:" prop="estimatedTransactionAmount">
            <el-input :disabled="isView" v-model="form.estimatedTransactionAmount" placeholder="预计成交金额"></el-input>
          </el-form-item>
          <el-form-item label="跟单人:" prop="followUserId">
            <el-select :disabled="isView" v-model="form.followUserId" clearable reserve-keyword placeholder="请选择跟单人">
              <el-option v-for="item in assistList" :key="item.userId" :label="item.realityName" :value="item.userId + ''" />
            </el-select>
          </el-form-item>
          <el-form-item label="预计成交时间:" prop="estimatedBuyDateEnd">
            <el-date-picker
              style="width: 116px!important"
              v-model="form.estimatedBuyDateStart"
              :disabled="isView || !form.id"
              value-format="YYYY-MM-DD hh:mm:ss"
              type="date"
              placeholder="开始时间"
            ></el-date-picker>
             ~ 
            <el-date-picker
              style="width: 116px!important"
              v-model="form.estimatedBuyDateEnd"
              :disabled="isView"
              value-format="YYYY-MM-DD hh:mm:ss"
              type="date"
              placeholder="结束时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="协助人:" prop="assistUserId">
            <el-input v-model="form.assistUserId" v-show="false" placeholder="" size="normal" clearable></el-input>

            <el-select
              :disabled="isView"
              multiple
              v-model="assistUserIds"
              value-key=""
              placeholder="请选择协助人"
              clearable
              filterable
              @change="changeAssist"
            >
              <el-option v-for="item in assistList" :key="item.userId" :label="item.realityName" :value="item.userId + ''"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="需求:" prop="remark">
            <el-input :disabled="isView" type="textarea" style="width: 1043px" :rows="4" v-model="form.remark"></el-input>
          </el-form-item>
          <el-form-item label="项目背景:" prop="projectBackground">
            <el-input :disabled="isView" type="textarea" style="width: 1043px" :rows="4" v-model="form.projectBackground"></el-input>
          </el-form-item>
        </el-card>
      </el-form>
      <el-card class="box-card" shadow="always">
        <template #header>
          <el-button :disabled="isView" type="primary" @click="handleAdd">添加商品</el-button>
          <el-button :disabled="isView" v-if="multiple" type="danger" @click="handleBatchDelete">删除</el-button>
        </template>
        <el-table border :data="dataSource" @selection-change="handleSelectionChange" show-summary>
          <el-table-column type="selection" width="55" align="center" :selectable="selectHandle" />
          <el-table-column label="#" type="index" width="55" align="center"> </el-table-column>
          <el-table-column label="商品图片" align="center" min-width="120">
            <template #default="scope">
              <ImagePreview :width="100" :height="100" :src="scope.row.packImg" :preview-src-list="[scope.row.packImg]" />
            </template>
          </el-table-column>
          <el-table-column label="商品名称" align="left" prop="goodsName" min-width="200" />
          <el-table-column label="商品品牌" align="center" prop="brandName" />
          <el-table-column label="商品数量" align="center" prop="quantity">
            <template #default="scope">
              <el-input
                @change="quantityChange($event, scope.row, scope.$index)"
                v-model="scope.row.quantity"
                placeholder="请输入商品数量"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="商品价格" align="center" prop="price">
            <template #default="scope">
              <el-input @change="quantityChange($event, scope.row, scope.$index)" v-model="scope.row.price" placeholder="请输入商品价格"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="金额" align="center" prop="amount" />
          <el-table-column label="毛利" align="center" prop="maoli" />
          <!-- <el-table-column label="上架状态" align="center" width="200">
          <template #default="scope">
            {{ selectDictLabel(material_audit_status, scope.row.auditStatus || '') }}
          </template>
        </el-table-column> -->
          <!-- <el-table-column label="集采成本价" align="center" prop="costPrice" />
          <el-table-column label="批发价" align="center" prop="wholesalePrice" /> -->
          <el-table-column label="备注" align="center" prop="remark">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="(isView = false), (title = '编辑跟单')" v-if="isView">编辑</el-button>
        <el-button type="primary" @click="up" v-if="isView && isList">上一张</el-button>
        <el-button type="primary" @click="down" v-if="isView && isList">下一张</el-button>
        <el-button type="primary" @click="submitForm" v-if="!isView">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import selectMaterialForm from '@/views/goods/quote/modules/selectMaterialForm';
  import customDialog from '@/views/goods/customer/modules/custom-dialog.vue';
import modelMixin from '@/mixins/modelMixin';
import clue, { getClueCode } from '@/api/goods/clue';
import { getClueSourceAllList } from '@/api/goods/clueSource';
import ImagePreview from '@/components/ImagePreview/index.vue';
import { provinceAndCityData, pcTextArr, regionData, pcaTextArr, codeToText } from 'element-china-area-data';
import { getSupplier } from '@/api/goods/supplier';
import { listFollowType } from '@/api/goods/followType';
import { listByTypeId } from '@/api/goods/followStage';
import { getUserNotPermission } from '@/api/system/user';
import moment from 'moment';
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();
export default {
  name: 'addForm',
  components: {
    selectMaterialForm,
    ImagePreview,
    customDialog
  },
  mixins: [modelMixin],
  data() {
    return {
      open: false,
      title: '添加跟单',
      funcObj: clue,
      multiple: false,
      isView: false,
      selectedRows: [],
      assistUserIds: [],
      contacts: [],
      form: {},
      isList:true,//是否从列表查询
      supplierOptions: [], //客户
      quotationSchemeOptions: [], //方案
      dateRange: [],
      rules: {
        followTypeId: [
          {
            required: true,
            message: '请选择跟单类型',
            trigger: 'blur'
          }
        ],
        followDate: [
          {
            required: true,
            message: '请选择跟单日期',
            trigger: 'blur'
          }
        ],
        supplierId: [
          {
            required: true,
            message: '请选择报价客户',
            trigger: 'blur'
          }
        ],
        clueSource: [
          {
            required: true,
            message: '请选择跟单来源',
            trigger: 'blur'
          }
        ],
        clueName: [
          {
            required: true,
            message: '请选择项目名称',
            trigger: 'blur'
          }
        ],
        followStageId: [
          {
            required: true,
            message: '请选择跟单阶段',
            trigger: 'blur'
          }
        ],
        remark: [
          {
            required: true,
            message: '请输入项目需求',
            trigger: 'blur'
          }
        ],
        followUserId: [
          {
            required: true,
            message: '请选择跟单人',
            trigger: 'blur'
          }
        ],
        estimatedTransactionAmount: [
          {
            required: true,
            message: '请输入预计交易金额',
            trigger: 'blur'
          }
        ]
      },
      queryParams: {
        categoryId: '',
        categoryName: ''
      },
      active: 1,
      baseInput: 200,
      data: [],
      dateRange: [],
      dataSource: [],
      loading: false,
      quote_status: [], //报价状态
      options: regionData,
      selectedOptions: [],
      clueSource: [],
      currentIndex: 0,
      data: [],
      followTypeList: [],
      assistList: [],
      followStatus: [] //跟单阶段
    };
  },
  created() {
    this.getSupplierAllList(1);
    this.listFollowType();
    this.getArea();
    this.getUserNotPermission();
  },
  methods: {
    add(info) {
      this.open = true;
      this.isView = false;
      this.title = '添加跟单'
        this.form = { 
          followTypeId: info.id,
           followUserId: userStore.userId + '', 
           followDate: moment().format('YYYY-MM-DD hh:mm:ss'),
           estimatedBuyDateStart:moment().format('YYYY-MM-DD hh:mm:ss'),
        }
      this.dataSource = [];
      this.selectedOptions = [];
      this.assistUserIds = [];
      this.addInit();
      this.getClueSourceAllList();
      if (info.id) {
        this.getFollowStatus(info.id);
      }
    },
    async edit(row) {
      this.open = true;
      this.isView = false;
      (this.title = '编辑跟单'), (this.form = {});
      this.dataSource = [];
      this.selectedOptions = [];
      this.getClueSourceAllList();
      this.getDetail(row);
      this.getFollowStatus(row.followTypeId);
      // 客户信息

      const res = await this.getSupplier(row.supplierId);
      this.contacts = (res && res.supplierContactList) || [];
    },
    view(row, index, data) {
      this.open = true;
      this.currentIndex = index;
      this.data = data;
      console.log('this.index :>> ', index);
      (this.title = '查看跟单'), (this.form = {});
      this.dataSource = [];
      this.selectedOptions = [];
      this.isView = true;
      this.getClueSourceAllList();
      this.getDetail(row);
    },

    changeAssist(val) {
      this.form.assistUserId = val.join(',');
    },
    // 根据跟单类型获取跟单阶段
    getFollowStatus(id) {
      listByTypeId(id).then((res) => {
        this.followStatus = (res || []).sort((a, b) =>{
          const getNum = (val)=>{
            return +(val.replace('%',''))
          }
          return getNum(a.progressCoefficient) - getNum(b.progressCoefficient);
        });
      });
    },
    // 获取跟单类型
    listFollowType() {
      listFollowType({
        pageSize: 1000,
        pageNum: 1,
        typeCategory:1
      }).then((res) => {
        this.followTypeList = res.rows;
      });
    },
    down() {
      this.currentIndex = this.currentIndex + 1;
      console.log('this.currentIndex :>> ', this.data);
      if (this.currentIndex >= this.data.length) {
        this.$message({
          type: 'info',
          message: '已经是最后一张'
        });
        this.currentIndex = this.data.length - 1;
      } else {
        this.getDetail(this.data[this.currentIndex]);
      }
    },
    up() {
      this.currentIndex = this.currentIndex - 1;
      if (this.currentIndex < 0) {
        this.$message({
          type: 'info',
          message: '已经是第一张'
        });
        this.currentIndex = 0;
      } else {
        this.getDetail(this.data[this.currentIndex]);
      }
    },
    detailAfter() {
      this.dataSource = this.form.jzgClueMaterialVoList;
      this.selectedOptions = this.form.country.split(',');
      this.form.followUserId = this.form.followUserId + '';
      this.assistUserIds = this.form.assistUserId ? this.form.assistUserId.split(',') : [];
      this.getFollowStatus(this.form.followTypeId);
      this.customerChange(this.form.supplierId);
    },
    cancel() {
      this.open = false;
    },
    categoryChange(value) {
      this.form.categoryId = value;
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
      this.multiple = val.length > 0;
    },
    selectHandle(row) {
      return 1;
    },
    handleAdd() {
      this.$refs.selectMaterialForm.show();
    },
    
    showCustomer() {
      this.$refs.customDialog.open();
    },
    selectOk(data) {
      this.dataSource = data.map((v) => {
        let data = {
          ...v,
          clueId: this.$route.query.id || '',
          goodsId: v.id,
          price: v.retailPrice,
          surrogateStatus: v.supplyMode,
          shelfStatus: v.auditStatus,
          costPrice: v.costPrice,
          wholesalePrice: v.wholesalePrice
        };
        delete data.id;
        return data;
      });
    },
    
    customerOk(rows) {
      let customer = rows[0];
      this.form.supplierId = customer.id;
      this.form.supplierName = customer.supplierName;
      this.form.country = customer.saleArea;
      this.customerChange(this.form.supplierId);
    },
    remoteMethod(query, listKey, key) {
      const optionKey = listKey + 'Options';
      if (query !== '') {
        this[optionKey] = this[listKey + 'List'].filter((item) => {
          return item[key].toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
      } else {
        this[optionKey] = this[listKey + 'List'];
      }
    },

    // 获取线索单号
    addInit() {
      getClueCode().then((res) => {
        this.form.clueNumber = res.data;
      });
    },
    classifyForm() {
      this.form.jzgClueMaterialList = this.dataSource;
      // // 价格
      this.form.amount = this.dataSource.reduce((total, item) => {
        return total + +item.amount;
      }, 0);
      // // 金额
      // this.form.quotationPrice = this.dataSource.reduce((total, item) => {
      //   return total + +item.wholesalePrice
      // }, 0)
      // this.form.country = this.selectedOptions.join(',');
    },

    /**
     * @批量删除
     */
    handleBatchDelete() {
      if (this.selectedRows.length == 0) {
        this.$modal.msgError('请选择要删除的数据');
        return;
      }
      var ids = this.selectedRows.map((item) => item.goodsId).join(',');
      this.$modal
        .confirm('是否删除选中的数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          this.dataSource = this.dataSource.filter((item) => !ids.includes(item.goodsId));
        })
        .catch(() => {
          this.$modal.messageError({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    quantityChange(value, row, index) {
      row.amount = row.price * row.quantity;
      this.dataSource.splice(index, 1, row);
    },
    getClueSourceAllList() {
      getClueSourceAllList().then((res) => {
        this.clueSource = res;
      });
    },
    getSupplier(id) {
      return new Promise((resolve, reject) => {
        getSupplier(id).then((res) => {
          console.log('res :>> ', res);
          resolve(res.data);
        });
      });
    },
    async customerChange(val) {
      if (!val) return;
      const res = await this.getSupplier(val);
      this.contacts = (res && res.supplierContactList) || [];
      if (this.contacts.length) {
        this.form.contact = this.contacts[0].id;
        this.form.contactWay = this.contacts[0].phone;
        this.form.postName = this.contacts[0].postName;
      }
      this.form.addDetail = res.addDetail;
      this.form.country = res.saleArea;
      this.form.supplierName = res.supplierName;
    },
    contactChange(val) {
      const index = this.contacts.findIndex((item) => item.name === val);
      if (index !== -1) {
        this.form.contactWay = this.contacts[index].phone;
      }
    },
    // 后台用户
    getUserNotPermission() {
      getUserNotPermission()
        .then((res) => {
          this.assistList = res;
        })
        .catch((err) => {
          console.log(err);
        });
    }
  }
};
</script>

<style lang="scss" scoped></style>